package cinema;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Manager extends User {
    public Manager(String userId, String username, String password, Date registerTime,
                   String userType, String phone) {
        super(userId, username, password, registerTime, userType, phone);
    }

    // 重置前台密码
    public boolean resetReceptionistPassword(List<User> users, String username) {
        Optional<User> receptionist = users.stream()
                .filter(u -> u.getUsername().equals(username) && "前台".equals(u.getUserType()))
                .findFirst();

        if (receptionist.isPresent()) {
            receptionist.get().setPassword("123456");
            System.out.println("密码已重置为123456，用户登录时需修改");
            new Log("重置前台密码: " + username, this.getUsername()).recordLog();
            return true;
        }

        System.out.println("未找到该前台用户");
        return false;
    }

    // 添加影片
    public void addMovie(List<Movie> movies, Scanner scanner) {
        System.out.println("请输入片名：");
        String name = scanner.next();
        System.out.println("请输入导演：");
        String director = scanner.next();
        System.out.println("请输入主演：");
        String actor = scanner.next();
        System.out.println("请输入剧情简介：");
        scanner.nextLine(); // 吸收换行
        String intro = scanner.nextLine();
        System.out.println("请输入时长（分钟）：");
        int duration = getIntInput(scanner);
        System.out.println("请输入评分（0-10分）：");
        double rating = getDoubleInput(scanner);

        movies.add(new Movie(name, director, actor, intro, duration, rating));
        System.out.println("影片添加成功");
    }

    // 列出所有影片
    public void listAllMovies(List<Movie> movies) {
        System.out.println("影片列表：");
        movies.forEach(movie -> System.out.println(movie.getMovieInfo()));
    }

    // 修改影片信息
    public void modifyMovie(List<Movie> movies, String name) {
        Movie movie = findMovie(movies, name);
        if (movie == null) {
            System.out.println("未找到该影片");
            return;
        }

        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择修改内容：1.导演 2.主演 3.剧情简介 4.时长 5.评分");
        int choice = getIntInput(scanner);

        switch (choice) {
            case 1 -> {
                System.out.println("请输入新导演：");
                movie.setDirector(scanner.nextLine());
            }
            case 2 -> {
                System.out.println("请输入新主演：");
                movie.setActors(scanner.nextLine());
            }
            case 3 -> {
                System.out.println("请输入新剧情简介：");
                movie.setIntroduction(scanner.nextLine());
            }
            case 4 -> {
                System.out.println("请输入新时长（分钟）：");
                movie.setDuration(getIntInput(scanner));
            }
            case 5 -> {
                System.out.println("请输入新评分（0-10分）：");
                movie.setRating(getDoubleInput(scanner));
            }
            default -> {
                System.out.println("输入错误");
                return;
            }
        }
        System.out.println("修改成功");
    }

    // 删除影片
    public boolean deleteMovie(List<Movie> movies, String name, List<Schedule> schedules) {
        Movie movie = findMovie(movies, name);
        if (movie == null) {
            System.out.println("未找到该影片");
            return false;
        }

        if (hasScheduledScreenings(schedules, name)) {
            System.out.println("该影片已有排片，无法删除");
            return false;
        }

        Scanner scanner = new Scanner(System.in);
        System.out.println("确定要删除影片" + name + "吗？删除后无法恢复（y/n）");
        if (!"y".equalsIgnoreCase(scanner.next())) {
            System.out.println("取消删除");
            return false;
        }

        movies.remove(movie);
        System.out.println("删除成功");
        return true;
    }

    // 查询影片
    public void queryMovie(List<Movie> movies, String condition, String value) {
        Predicate<Movie> predicate = switch (condition) {
            case "片名" -> m -> m.getName().equals(value);
            case "导演" -> m -> m.getDirector().equals(value);
            case "主演" -> m -> m.getActors().equals(value);
            default -> m -> false;
        };

        List<Movie> results = movies.stream()
                .filter(predicate)
                .collect(Collectors.toList());

        if (results.isEmpty()) {
            System.out.println("未找到匹配影片");
            return;
        }

        System.out.println("查询结果：");
        results.forEach(m -> System.out.println(m.getMovieInfo()));
    }

    // 添加场次
    public void addSchedule(List<Schedule> schedules, Movie movie, Hall hall, Date time, double price) {
        String scheduleId = "SCH" + System.currentTimeMillis();
        schedules.add(new Schedule(scheduleId, movie, hall, time, price));
        System.out.println("场次添加成功");
    }

    // 查看当日销售数据
    public void viewTodaySales(List<Ticket> tickets) {
        Date today = new Date();
        List<Ticket> todayTickets = tickets.stream()
                .filter(t -> isSameDay(t.getSaleTime(), today))
                .collect(Collectors.toList());

        int totalTickets = 0;
        double totalAmount = 0.0;
        int refundCount = 0;
        double refundAmount = 0.0;

        for (Ticket ticket : todayTickets) {
            if (ticket.isRefunded()) {
                refundCount++;
                refundAmount += ticket.getPrice() * 0.9; // 假设扣10%手续费
            } else {
                totalTickets++;
                totalAmount += ticket.getPrice();
            }
        }

        System.out.println("当日销售数据：");
        System.out.println("总售票数：" + totalTickets);
        System.out.println("总金额：" + String.format("%.2f", totalAmount));
        System.out.println("退票数：" + refundCount);
        System.out.println("退票金额：" + String.format("%.2f", refundAmount));
    }

    //============ 辅助方法 ============//
    private Movie findMovie(List<Movie> movies, String name) {
        return movies.stream()
                .filter(m -> m.getName().equals(name))
                .findFirst()
                .orElse(null);
    }

    private boolean hasScheduledScreenings(List<Schedule> schedules, String movieName) {
        return schedules.stream()
                .anyMatch(s -> s.getMovie().getName().equals(movieName));
    }

    private int getIntInput(Scanner scanner) {
        while (true) {
            try {
                return scanner.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("请输入有效整数");
                scanner.nextLine(); // 清除无效输入
            }
        }
    }

    private double getDoubleInput(Scanner scanner) {
        while (true) {
            try {
                return scanner.nextDouble();
            } catch (InputMismatchException e) {
                System.out.println("请输入有效数字");
                scanner.nextLine(); // 清除无效输入
            }
        }
    }

    // 使用Calendar进行日期比较
    private boolean isSameDay(Date d1, Date d2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(d1);
        cal2.setTime(d2);
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
    }
}